package com.hsc.mvc.handler;

import com.alibaba.fastjson.JSON;
import com.hsc.mvc.annotations.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author
 * @date 2025-06-10
 * @Description 对象处理响应器。会处理成json字符串，再直接响应
 * 方法标注有ResponseBody 的注解
 */
public class ObjectResultHandler implements ResponseHandleStrategy {
    @Override
    public boolean isSupport(Object result, Method targetMethod) {
        return targetMethod.getAnnotation(ResponseBody.class) != null;
    }

    @Override
    public void handle(Object result, Method targetMethod, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 将返回对象转为json字符串
        String json = JSON.toJSONString(result);
        // 设置字符集 支持中文
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);
    }
}
